package com.hunliji.monitor.web.mq.rocket;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.gson.internal.LinkedTreeMap;
import com.hunliji.monitor.manager.api.FeiShuManager;
import com.hunliji.monitor.manager.api.FeishuInterceptionManager;
import com.hunliji.monitor.manager.api.model.param.FeiShuSendMsgManagerParam;
import com.hunliji.monitor.share.component.mq.rocket.constants.RocketMqConstants;
import com.hunliji.monitor.share.enums.ReceiveIdTypeEnum;
import com.hunliji.monitor.share.enums.feishu.InterceptEventTypeEnum;
import com.hunliji.monitor.web.config.FeishuIssuePushConfig;
import com.hunliji.monitor.web.facade.FeiShuFacade;
import com.lark.project.service.field.model.FieldValuePair;
import com.lark.project.service.workitem.model.WorkItemInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.BooleanUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RocketMQMessageListener(
        topic = RocketMqConstants.TOPIC_FEISHU_DELAY,
        consumerGroup = RocketMqConstants.GROUP_FEISHU_DELAY,
        selectorExpression = RocketMqConstants.TAG_FEISHU_DELAY)
@Slf4j
public class FeishuDelayMessageListener implements RocketMQListener<String> {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private FeiShuManager feiShuManager;

    @Resource
    private FeiShuFacade feiShuFacade;

    @Resource
    private FeishuIssuePushConfig feishuIssuePushConfig;

    @Resource
    private FeishuInterceptionManager feishuInterceptionManager;

    @Override
    public void onMessage(String s) {
        log.info("FeishuDelayMessageListener receive msg:{}", s);

        JSONObject jsonObject = JSON.parseObject(s);
        JSONObject data = jsonObject.getJSONObject("data");
        Long workItemId = data.getLong("workItemId");
        String projectKey = data.getString("projectKey");
        String workItemTypeKey = data.getString("workItemTypeKey");
        Integer type = data.getInteger("type");
        String key = getFeishuDelayKey(workItemId, type);
        String interceptionAccessToken = feishuInterceptionManager.getAccessToken();
        WorkItemInfo workItemInfo = feishuInterceptionManager.getWorkItemInfo(interceptionAccessToken, workItemId, projectKey, workItemTypeKey);
        if (workItemInfo == null) {
            log.warn("工作项不存在,data={}", data.toJSONString());
            return;
        }

        // 判断是否延迟告警
        if (InterceptEventTypeEnum.CREATE_WORK_ITEM.getEventType().equals(type)) {
            // 缺陷创建：5分钟未响应，缺陷resolve，经办人不在白名单内
            if (BooleanUtils.isTrue(stringRedisTemplate.hasKey(key))) {
                log.info("5分钟内及时相应,不做延迟告警,data={}", data.toJSONString());
                return;
            }
            if ("RESOLVED".equals(workItemInfo.getSubStage()) || "CLOSED".equals(workItemInfo.getSubStage())) {
                log.info("缺陷已resolve或close,不做延迟告警, data={}, workItemInfo={}", data.toJSONString(), workItemInfo);
                return;
            }
            List<String> operatorList = parseOperatorList(workItemInfo.getFields());
            if (isAnyOperatorNotInWhiteList(operatorList)) {
                log.info("缺陷已转开发处理,不做延迟告警,data={}, workItemInfo={}", data.toJSONString(), workItemInfo);
                return;
            }
        }else if (InterceptEventTypeEnum.UPDATE_STATE.getEventType().equals(type)) {
            // 缺陷解决：2小时内未响应，缺陷未close
            if (BooleanUtils.isTrue(stringRedisTemplate.hasKey(key))) {
                log.info("2小时内及时相应,不做延迟告警,data={}, workItemInfo={}", data.toJSONString(), workItemInfo);
                return;
            }
            if ("CLOSED".equals(workItemInfo.getSubStage())) {
                log.info("缺陷已close,不做延迟告警,data={}, workItemInfo={}", data.toJSONString(), workItemInfo);
                return;
            }
        }else {
            // 其他任何事件都不进行延迟告警
            return;
        }

        // 开始延迟告警
        sendDelayWarn(data.getString("issueName"), data.getString("messageId"));
    }

    /**
     * 当前经办人是否包含非测试人员
     */
    private boolean isAnyOperatorNotInWhiteList(List<String> operatorList) {
        if (CollectionUtils.isEmpty(operatorList)) {
            return false;
        }
        String operatorTestIds = feishuIssuePushConfig.getOperatorTestIds();
        for (String operator : operatorList) {
            if (!operatorTestIds.contains(operator)) {
                return true;
            }
        }
        return false;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    private List<String> parseOperatorList(List<FieldValuePair> fields) {
        FieldValuePair fieldValuePair = fields.stream().filter(field -> "role_owners".equals(field.getFieldKey())).findFirst().orElse(null);
        if (fieldValuePair == null || !(fieldValuePair.getFieldValue() instanceof ArrayList)) {
            return Lists.newArrayList();
        }
        List<LinkedTreeMap<String, Object>> roleOwners = (ArrayList) fieldValuePair.getFieldValue();
        LinkedTreeMap<String,  Object> operator = roleOwners.stream().filter(treeMap -> "operator".equals(treeMap.get("role"))).findFirst().orElse(null);
        if (operator == null || MapUtils.isEmpty(operator)) {
            return Lists.newArrayList();
        }
        Object owners = operator.get("owners");
        if (owners == null) {
            return Lists.newArrayList();
        }
        return (ArrayList)owners;
    }

    private void sendDelayWarn(String issueName, String messageId) {
        // 飞书推送
        String accessToken = feiShuFacade.getAccessToken();
        FeiShuSendMsgManagerParam feiShuSendMsgManagerParam = new FeiShuSendMsgManagerParam();
        feiShuSendMsgManagerParam.setMsgType("text");
        JSONObject content = new JSONObject();
        content.put("text", "缺陷【" + issueName + "】超时未跟进");
        feiShuSendMsgManagerParam.setContent(content.toJSONString());
        feiShuSendMsgManagerParam.setReceiveId(feishuIssuePushConfig.getChatId());
        feiShuSendMsgManagerParam.setReceiveIdType(ReceiveIdTypeEnum.CHAT_ID.getCode());
        feiShuManager.sendMsg(feiShuSendMsgManagerParam, accessToken);

        // 打电话
        // List<String> userIdList = Arrays.stream(feishuIssuePushConfig.getUserOpenIds().split(",")).collect(Collectors.toList());
        // feiShuManager.urgentPhone(userIdList, messageId, accessToken);
    }

    private String getFeishuDelayKey(Long workItemId, Integer type) {
        return "FeishuDelay:" + workItemId + "_" + type;
    }
}
